package com.sam.security.component;

import com.sam.security.dto.UserDetail;
import com.sam.security.entity.UserEntity;
import com.sam.security.service.MenuService;
import com.sam.security.service.RoleService;
import com.sam.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @classname: CustomAuthenticationService
 * @description: TODO
 * @Author: sam
 * @date: 2021/4/17 18:04
 */
@Component
public class CustomUserDetailService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private MenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserEntity userEntity = userService.queryByUserName(username);
        if (userEntity == null) {
            throw new UsernameNotFoundException("用户名不对");
        }
        // 获取角色列表
        List<String> roleCodes = roleService.queryByUserName(username);

        // 获取权限列表
        List<String> authorities = menuService.queryMenuByRoleCods(roleCodes);

        roleCodes = roleCodes.stream().map(item -> "ROLE_" + item).collect(Collectors.toList());
        authorities.addAll(roleCodes);

        UserDetail detail = new UserDetail();
        detail.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(String.join(",",authorities)));
        detail.setUsername(userEntity.getAccountCode());
        detail.setPassword(userEntity.getPassword());
        return detail;
    }
}
